package com.bigmodel.taskmanager;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bigmodel.baidu.BaiduWenXin;
import com.bigmodel.baidu.Chatglm2;
import com.bigmodel.baidu.MarkdownUtil;
import com.bigmodel.util.FtlUtil;
import com.bigmodel.vo.RequestAmdbAttrVO;
import org.junit.Test;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class TaskService3 {

    private final static String TASK_LIST_ATTR_NAME="任务";
    private final static String TASK_ATTR_ID="任务ID";
    private final static String TASK_ATTR_DEPENDENT="依赖任务ID";
    private final static String TASK_ATTR_INPUT="输入";

    private final static String TASK_ATTR_TOOL = "工具";
    private final static String TASK_ATTR_OPERATION="操作";
    private final static String TASK_ATTR_OBSERVE="观察结果";
    private final static String TASK_ATTR_DESCRIBE="任务描述";
    
    private final static String BASE_URL = "http://localhost:8888/api";

    /**执行任务
     *
     * @param taskJson
     */
    public void execute(String faultInfo ,String taskJson,List<Task> historyTaskList){
        JSONObject taskLink = JSONUtil.parseObj(taskJson);
        JSONArray taskListJson = taskLink.getJSONArray(TASK_LIST_ATTR_NAME);

        HashMap<String,Object> onceMemory = new HashMap<>();

        /*-----------step1 组装任务链-------------*/
        List<Task> allTask = createTaskChain(taskListJson);

        /*-----------step2 查询第一个任务-------------*/
        List<Task> gptNextTaskList = new ArrayList<>();
        for(Task task : allTask){
            if("任务1".equals(task.getTaskId())){
                gptNextTaskList.add(task);
            }
        }

        /*-----------step4 遍历执行任务队列-------------*/
        while (!gptNextTaskList.isEmpty()) {

            StringBuffer sbResponse = new StringBuffer();
            for(Task task : gptNextTaskList) {
                System.out.println();
                System.out.println();
                System.out.println();
                System.out.println("AI AGENT: ========================================开始执行新任务==========================================");
                System.out.println("AI AGENT: 我准备做以下任务" );
                System.out.println("AI AGENT: 任务信息-任务名称[" + task.getTaskContent() + "]");
                System.out.println("AI AGENT: 任务信息-使用工具[" + task.getTaskTool() + "]");
                System.out.println("AI AGENT: 任务信息-输入参数[" + task.getInputParam() + "]");

                String response = "";
                if (ToolEnum2.findInstance.getName().equals(task.getTaskTool())) {
                    response = findInstance(task.getInputParam());
                    response = "我使用" + task.getTaskTool() + "得到结果：" + response;
                    System.out.println("AI AGENT: 执行结果-" + response);
                } else if (ToolEnum2.getInstanceStatus.getName().equals(task.getTaskTool())) {
                    JSONObject jsonObject = JSONUtil.parseObj(task.getInputParam());
                    response = getInstanceStatus(jsonObject.getStr("name"));
                    response = "我使用" + task.getTaskTool() + "得到结果：" + response;
                    System.out.println("AI AGENT: 执行结果-" + response);
                } else if (ToolEnum2.restartInstance.getName().equals(task.getTaskTool())) {
                    JSONObject jsonObject = JSONUtil.parseObj(task.getInputParam());
                    response = restartInstance(jsonObject.getJSONArray("name").toList(String.class));
                    response = "我使用" + task.getTaskTool() + "得到结果：" + response;
                    System.out.println("AI AGENT: 执行结果-" + response);
                } else if (ToolEnum2.findDB.getName().equals(task.getTaskTool())) {
                    JSONObject jsonObject = JSONUtil.parseObj(task.getInputParam());
                    response = findDB("业务分析系统");
                    response = "我使用" + task.getTaskTool() + "得到结果：" + response;
                    System.out.println("AI AGENT: 执行结果-" + response);
                } else if (ToolEnum2.getDbStatus.getName().equals(task.getTaskTool())) {
                    JSONObject jsonObject = JSONUtil.parseObj(task.getInputParam());
                    response = getDbStatus(jsonObject.getJSONArray("name").toList(String.class));
                    response = "我使用" + task.getTaskTool() + "得到结果：" + response;
                    System.out.println("AI AGENT: 执行结果-" + response);
                } else if (ToolEnum2.restartDb.getName().equals(task.getTaskTool())) {
                    JSONObject jsonObject = JSONUtil.parseObj(task.getInputParam());
                    response = restartDb(jsonObject.getJSONArray("name").toList(String.class));
                    response = "我使用" + task.getTaskTool() + "得到结果：" + response;
                    System.out.println("AI AGENT: 执行结果-" + response);
                }

                sbResponse.append(response);
                sbResponse.append("\r\n");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("faultInfo", faultInfo);
            map.put("taskDescribe", gptNextTaskList.get(0).getTaskContent());
            map.put("taskResult", sbResponse.toString());
            String questionContent = FtlUtil.generateContent(map, "autotask/v2/predictv3/basequestion.ftl");
            String answerContent = Chatglm2.chatMock(questionContent);

            List<Task> nextTaskList = gptNextTaskList.get(0).getNextTask();

            /*-----------------------得到回复后组装下个任务--------------------------------*/
            if (ObjectUtil.isNotEmpty(answerContent)) {
                gptNextTaskList = new ArrayList<>();
                try {
                    JSONObject taskObj = JSONUtil.parseObj(answerContent);
                    Task nextTask  = new Task();
                    nextTask.setTaskTool(taskObj.getStr(TASK_ATTR_TOOL));
                    nextTask.setInputParam(taskObj.getJSONObject(TASK_ATTR_INPUT).toString());
                    gptNextTaskList.add(nextTask);
                } catch (Exception e) {
                    JSONArray jsonArray = JSONUtil.parseArray(answerContent);
                    for(int i =0; i < jsonArray.size();i++){
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        Task nextTask = new Task();
                        nextTask.setTaskTool(jsonObject.getStr(TASK_ATTR_TOOL));
                        nextTask.setInputParam(jsonObject.getJSONObject(TASK_ATTR_INPUT).toString());
                        gptNextTaskList.add(nextTask);
                    }
                }

                if(!gptNextTaskList.isEmpty()){
                    for(Task gptTask : gptNextTaskList){
                        for(Task configTask : nextTaskList){
                            if(gptTask.getTaskTool().equals(configTask.getTaskTool())){
                                gptTask.setTaskContent(configTask.getTaskContent());
                            }
                        }
                    }
                }
            } else {
                gptNextTaskList.clear();
            }

        }

    }

    /**
     * 组装任务链
     * @param taskListJson
     * @return
     */
    private List<Task> createTaskChain(JSONArray taskListJson){
        List<Task> allTask = new ArrayList<>();
        for(int i = 0 ; i < taskListJson.size() ; i++){
            JSONObject obj = taskListJson.getJSONObject(i);
            Task task = new Task();
            task.setTaskId(obj.getStr(TASK_ATTR_ID));
            task.setTaskName(obj.getStr(TASK_ATTR_OPERATION));
            task.setTaskTool(obj.getStr(TASK_ATTR_OPERATION));
            task.setTaskContent(obj.getStr(TASK_ATTR_DESCRIBE));
            task.setInputParam(obj.getStr(TASK_ATTR_INPUT));
            task.setDependentTaskIds(obj.getJSONArray(TASK_ATTR_DEPENDENT).toList(String.class));
            allTask.add(task);
        }
        Map<String, Task> taskMap = allTask.stream().collect(Collectors.toMap(Task::getTaskId, Function.identity(), (key1, key2) -> key2));

        for(Task task : allTask){
            List<String> dependentTaskIds = task.getDependentTaskIds();
            if(ObjectUtil.isNotEmpty(dependentTaskIds)){
                dependentTaskIds.forEach(taskId->{
                    //获取依赖的前节点
                    Task preTask = taskMap.get(taskId);
                    //绑定前节点的下一节点
                    preTask.addNextTask(task);
                });
            }
        }

        return allTask;
    }


    public static void main(String[] args) {
        String taskJson = FileUtil.readString("D:\\javacode\\bigmodel\\bigmodel\\flow3.json", Charset.defaultCharset());
        System.out.println("========================================执行计划==========================================");
        System.out.println(taskJson);
        List<Task> historyTaskList = new ArrayList<>();
        TaskService3 taskService3 = new TaskService3();
        taskService3.execute("CRM系统成功率低于100%",taskJson,historyTaskList);

        StringBuffer stringBuffer = new StringBuffer();


        Map<String,Object> mapReport = new HashMap<>();
        mapReport.put("content",stringBuffer.toString());
        String report = BaiduWenXin.chat(FtlUtil.generateContent(mapReport, "autotask/v1/createReport.ftl"));
        System.out.println("AI AGENT: 最终报告:"+report);
    }




    public String getDbStatus(List<String> nameList) {
        String url = BASE_URL + "/testv3/getDbStatus";
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(nameList));

        Map<String, Object> map = new HashMap<>();
        map.put("apiResponse", result);
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/predictv3/toolresult/getDbStatus.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        return answerContent;
    }



    public String restartDb(List<String> nameList) {
        String url = BASE_URL + "/testv3/restartDb";
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(nameList));

        Map<String, Object> map = new HashMap<>();
        map.put("apiResponse", result);
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/predictv3/toolresult/restartDb.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        return answerContent;
    }

    public String receiveQuestion(String questionMessage) {


        String taskJson = FileUtil.readString("D:\\javacode\\bigmodel\\bigmodel\\flow3.json", Charset.defaultCharset());
        System.out.println("========================================执行计划==========================================");
        System.out.println(taskJson);
        List<Task> historyTaskList = new ArrayList<>();
        execute(questionMessage,taskJson,historyTaskList);

        StringBuffer stringBuffer = new StringBuffer();


        Map<String,Object> mapReport = new HashMap<>();
        mapReport.put("content",stringBuffer.toString());
        String report = BaiduWenXin.chat(FtlUtil.generateContent(mapReport, "autotask/v1/createReport.ftl"));
        System.out.println("AI AGENT: 最终报告:"+report);
        return report;

    }


    public String getInstanceStatus(String name) {
        String url = BASE_URL + "/testv3/getInstanceStatus?name="+name;
        String result = HttpUtil.get(url);

        Map<String, Object> map = new HashMap<>();
        map.put("apiResponse", result);
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/predictv3/toolresult/getInstanceStatus.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        return answerContent;
    }


    public String findInstance(String systemName) {
        String url = BASE_URL + "/testv3/findInstance?systemName=" + systemName;
        String result = HttpUtil.get(url);

        Map<String, Object> map = new HashMap<>();
        map.put("apiResponse", result);
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/predictv3/toolresult/findInstance.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        return answerContent;
    }

    public String restartInstance(List<String> nameList) {
        String url = BASE_URL + "/testv3/restartInstance";
        String result = HttpUtil.get(url);

        Map<String, Object> map = new HashMap<>();
        map.put("apiResponse", result);
        map.put("instanceName", "adminCenter");
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/predictv3/toolresult/restartInstance.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        return answerContent;
    }

    public String findDB(String systemName) {
        String url = BASE_URL + "/testv3/findDb?systemName=" + systemName;
        String result = HttpUtil.get(url);

        Map<String, Object> map = new HashMap<>();
        map.put("apiResponse", result);
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/predictv3/toolresult/findDb.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        return answerContent;
    }

    @Test
    public void t1() {
        String a = "aaa";
        String b = "aaa";
        System.out.println(StrUtil.similar(a,b));
    }
}
